<template>
    <div class="app-container">
         <el-card>
            <h4 v-if="rowData">{{ rowData.companyName }}</h4>
            <el-row gutter="10">
                <el-col :span="8" >
                    <Carousel v-bind="swiperData"></Carousel>
                </el-col>
                <el-col :offset="1" :span="15">
                    <el-row justify="start" align="middle">
                        <el-col :span="20" >
                            <div class="city-title text-ellipsis">{{ rowData.carryCityName }}</div>
                            <div class="city-content text-ellipsis">购箱城市：{{ rowData.carryCityName }}/{{ rowData.carryCountryName }}</div>
                        </el-col>
                       
                    </el-row>
                    <el-row  class="marginTop20" justify="start" align="middle">
                        <el-col :span="2">单价:</el-col>
                        <el-col :span="15">
                            <el-input v-model="param.unitPrice" style="max-width: 250px;color: #ff0000;" @input="handleInput" placeholder="请输入数字（最多7位，小数最多2位）" class="input-with-select">
                                <template #prepend>
                                    <el-select v-model="param.currency" placeholder="Select" style="width: 70px;color: #ff0000;">
                                        <el-option label="$" value="USD" />
                                        <el-option label="￥" value="CNY" />
                                    </el-select>
                                </template>
                            </el-input>
                        </el-col>
                    </el-row>
                    <el-divider  border-style="dashed"/>
                    <el-row  class="marginTop20" justify="start" align="middle">
                        <el-col :span="8">箱型：{{basicConfig.boxTypeInfo1[param.boxType]}} </el-col>
                        <el-col :span="8">箱况： {{basicConfig.boxConditionInfo2[param.boxCondition]}} </el-col>
                        <el-col :span="8">联系人： {{rowData.publisherName}}</el-col>
                        <el-col :span="8" class="marginTop20">联系电话：+{{rowData.publisherAreaCode}}  {{rowData.publisherTel}}</el-col>
                    </el-row>
                    <el-divider  border-style="dashed"/>
                    <el-row  class="marginTop20" justify="start" align="middle">
                        <el-col :span="2">数量:</el-col>
                        <el-col :span="15">
                            <el-input-number v-model="param.inventory" :min="1" :max="9999" @change="handleChange" />
                        </el-col>
                    </el-row>
                    <el-row  class="marginTop20" justify="start" align="middle">
                        <el-col :span="2">总额:</el-col>
                        <el-col :span="15" class="total">{{basicConfig.currency2[param.currency]}} {{ total }}</el-col>
                    </el-row>
                </el-col>
            </el-row>
        </el-card>
      
        <el-card class="marginTop20 marginBottom20">
            <span class="_before">订单信息</span>
            <el-row class="marginTop20" justify="start" align="middle">
                <el-col :offset="1" :span="2"  class="text-right"><span class="_asterisk">预计提箱日期： </span></el-col>
                <el-col :span="6">
                    <el-date-picker v-model="param.planPickupDate"  type="date" :disabled-date="disabledDate" placeholder="提箱日期" />
                </el-col>
                <el-col :span="2"  class="text-right"><span class="_asterisk">支付方式： </span></el-col>
                <el-col :span="5">
                    <el-select v-model="param.paymentMethod" style="width:200px">
                        <el-option label="对公转账" value="5"></el-option>
                        <el-option label="在线支付" value="10"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="2"  class="text-right"><span class="_asterisk">发票类型： </span></el-col>
                <el-col :span="6">
                    <el-select v-model="param.invoiceType" style="width:200px">
                        <el-option label="增值税普通发票" value="5"></el-option>
                        <el-option label="增值税专用发票" value="10"></el-option>
                        <el-option label="形式发票" value="15"></el-option>
                    </el-select>
                </el-col>
                <el-col :offset="1" :span="2"  class="text-right marginTop20"><span class="_asterisk">结算账期： </span></el-col>
                <el-col :span="6" class="marginTop20">
                    <el-input v-model="param.period" placeholder="请输入天数" @input="handlePeriodInput" style="width:200px">
                        <template #append>天</template>
                    </el-input>
                </el-col>
            </el-row>
            <el-divider  border-style="dashed"/>
            <el-row class="marginBottom20" align="middle">
                <el-col :offset="1" :span="2" class="text-right"><span class="_asterisk">经办人：</span></el-col>
                <el-col :span="6">{{nickName}}</el-col>
            </el-row>

            <el-row v-for="(item,index) in allocation" :key="index" align="middle" class="marginBottom10">
                <el-col :offset="1" :span="2" class="text-right"><span class="_asterisk">业务员：</span></el-col> 
                <el-col :span="5">
                    <el-select v-model="item.businessUserId" filterable style="width: 70%">
                        <el-option v-for="(user, index) in param.userSimpleList" :key="index" :label="user.nickname" :value="user.userId" />
                    </el-select>
                </el-col>
                <el-col :offset="1" :span="2" class="text-right"><span class="_asterisk">操作员：</span></el-col>
                <el-col :span="4">
                    <el-select v-model="item.operateUserId" filterable style="width: 75%">
                        <el-option v-for="(user, index) in param.userSimpleList" :key="index" :label="user.nickname" :value="user.userId" />
                    </el-select>
                </el-col>
                <el-col :offset="1" :span="2" class="text-right"><span class="_asterisk">业务编号：</span></el-col>
                <el-col :span="3">
                    <el-input v-model="item.businessNo" style="width: 100%" placeholder="请输入业务编号" maxlength="100"/>
                </el-col>
                <el-col :span="1" v-if="allocation.length >= 2" class="text-center"><el-icon :size="20" color="#2158F3" class="cursor"  @click="handleDelete(index)"><Remove /></el-icon></el-col> 
            </el-row>
            <el-row class="marginTop20" align="middle">
                <el-col :offset="2" :span="10" v-if="allocation.length <= 4"> <el-icon :size="25" color="#2158F3" class="cursor"  @click="handleAdd"><CirclePlus /></el-icon></el-col>
            </el-row>
            <el-divider  border-style="dashed"/>
            <span>留言</span>
            <el-input v-model.trim="param.remark" type="textarea" clearable show-word-limit maxlength="1000" rows="5" placeholder="请输入留言信息" class="marginTop10"/>
        </el-card>
          
        <el-affix position="bottom">
            <el-card>
                <el-row align="middle" justify="center">
                    <el-col :span="9"> 
                        <el-checkbox v-model="radioVal" size="large" />我已阅读<a style="color: #2020eb;" href="#">《集装箱租赁业务规则》</a><a style="color: #2020eb;" href="#">《用户服务协议和管理规则》</a>并同意全部条款
                    </el-col>
                    <el-col :span="2"><el-button type="primary" @click="handleSubmit">提交订单</el-button></el-col>
                </el-row>
            </el-card>   
        </el-affix>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, computed} from 'vue'
import  Carousel from '@/components/carousel'
import { getReleaseSalesInfo } from '@/api/boxDeal/boxSeel'
import { useRoute,useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import Cookies from 'js-cookie'
import { userSimpleList } from '@/api/user/index'
import  basicConfig from '@/constant/containerInfo';
import { addPurchaseBoxOrder } from '@/api/boxDeal/boxBuy'
const route = useRoute()
const router = useRouter()
const radioVal = ref(false) // 是否勾选业务条款
const rowData = ref({ // 集装箱基本信息
    id:'',
    companyName:'',
    carryCityName:'',
    carryCountryName:'',
    areaCode:'86',
    publisherName:'',
    publisherTel:'',
    releaseSaleId: '',
    
}) 
const allocation = ref([
    {
        businessUserId: '',           // 业务员id
        businessUserName: "",  // 业务员名称
        operateUserId:'' as string | number, // 操作员id
        operateUserName: "",   // 操作员名称
        businessNo: ""   // 业务编号
    }
])
interface UserSimple {
  userId: string | number
  nickname: string
}

const param = reactive({
    currency:'USD',
    unitPrice: 0,
    inventory: 1,
    planPickupDate:'',
    paymentMethod:'5',
    invoiceType:'',
    period:'30',
    businessNo:'',
    businessUserId:'5',
    operateUsers:'10',
    remark:'',
    boxType: route.query.boxType || '5',
    boxCondition: route.query.boxCondition || '5',
    total:'',
    userSimpleList:[] as UserSimple[]
})
const total = ref(0)
const  boxInfo = async()=> {
    if(!route.query.boxId) return ElMessage.warning('参数错误,请返回上一级并刷新页面')
    await getReleaseSalesInfo(route.query.boxId).then( res =>{ 
        if(res.code == '00000'){
            let _resData = res.data
            rowData.value = _resData
            param.planPickupDate = _resData.planPickupDate
            param.paymentMethod = _resData.paymentMethod || '5'
            param.period = _resData.period || '30'
            param.remark = _resData.remark
            swiperData.list = _resData.mainFileList? JSON.parse(_resData?.mainFileList) : []
            try{ 
                allocation.value = JSON.parse(_resData?.allocation) 
            }catch(e){

            }
            if(_resData?.releaseSalePriceList && route.query.boxType && route.query.boxCondition){
                _resData.releaseSalePriceList.forEach(item => { 
                    if(route.query.boxType == item.boxType && route.query.boxCondition == item.boxCondition ){
                        param.currency = item.currency
                        param.unitPrice = item.unitPrice
                        total.value = Number((item.unitPrice * param.inventory).toFixed(2))
                    }
                })
            }
            

        }else{
            ElMessage.warning(res.msg)
        }
    })

}

const swiperData = reactive({
  list: [],
  config: {
    width:"100%",
  }
})

const nickName = computed(()=>{
  return JSON.parse(Cookies.get("User-Info"))?.nickname
})
const companyRole = localStorage.getItem('companyRole')

onMounted(()=>{ 
    boxInfo()
    userSimpleList({}).then(res=>{ 
        if(res.code == '00000' && res.data.length > 0){
            param.userSimpleList = res.data
            localStorage.setItem('userSimpleList', JSON.stringify(res.data))
            allocation.value[0].operateUserId = Number(res.data[0].userId) 
        }
        
    })
})


const handleAdd = () => {  // 点击添加业务员/操作员/业务编号 信息
    if(allocation.value.length >= 5) return ElMessage.warning('最多添加5组业务员/操作员/业务编号')
    let itemInfo = {
        businessUserId: '',           // 业务员id
        businessUserName: "",  // 业务员名称
        operateUserId: '',            // 操作员id
        operateUserName: "",   // 操作员名称
        businessNo: ""   // 业务编号
    }
    allocation.value.push(itemInfo)

} 
const handleDelete = (sub:number) => {  // 点击删除业务员/操作员/业务编号 信息
    if(allocation.value.length <= 1) return ElMessage.warning('至少保留一组业务员/操作员/业务编号')
    allocation.value.splice(sub,1)
} 


const handleSubmit = async() => {  // 提交订单
    if(!radioVal.value) return ElMessage.warning('请先阅读《集装箱租赁业务规则》、《用户服务协议和管理规则》并同意全部条款')
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    let reqInfo = {
        releaseSaleId: rowData.value.id,
        unitPrice: param.unitPrice,
        boxType: param.boxType,
        boxCondition: param.boxCondition,
        currency: param.currency,
        boxQuantity: param.inventory,
        planPickupDate: param.planPickupDate,
        paymentMethod: param.paymentMethod,
        contacts: rowData.value.publisherName,
        invoiceType:param.invoiceType,
        tel: rowData.value.publisherTel,
        period: param.period,
        areaCode:rowData.value.areaCode,
        leaveMsg: param.remark,
        couponAmount: 0,
        allocation:  checkAllocation(allocation.value),
    }
    if(reqInfo.allocation){
        let allocationInfo:any = []
        try{ 
            allocationInfo = JSON.parse(reqInfo.allocation)
        } catch(e) {
            allocationInfo = reqInfo.allocation
        }

        if(!allocationInfo[0].businessNo || !allocationInfo[0].operateUserId || !allocationInfo[0].businessUserId){
            loading.close()
            return ElMessage.error('请完善业务员/操作员/业务编号')
        } 
   
    }else{
        loading.close()
        return ElMessage.error('请完善业务员/操作员/业务编号')
    }
    
    await addPurchaseBoxOrder(reqInfo).then((res:any)=>{ 
        if(res.code == "00000"){
            loading.close()
            ElMessage.success('下单成功！')
             if(companyRole=='zx'){ //货代
                router.push('/hdzxgm/agentBuyOrder');
            }else if(companyRole=='putBox'){
                router.push('/xdzxgm/agentBuyOrder');
            }
        }else{
            loading.close()
            ElMessage.error(res.msg)
        }  
    }).catch((error:any)=>{ 
     
        loading.close()
        ElMessage.error(error.msg)
    }).finally(()=>{
        loading.close()
    })

}

const checkAllocation = (allocation: any) => {
    try {
        allocation = JSON.parse(allocation)
    } catch (e) {
        allocation = allocation 
    }
    allocation.forEach((item) => { 
        param.userSimpleList.forEach(item1 => {
            if(item1.userId == item.businessUserId){
                item.businessUserName = item1.nickname
            }
            if(item1.userId == item.operateUserId){
                item.operateUserName = item1.nickname
            }
        })
    })
    return JSON.stringify(allocation) || allocation
}

const handleInput = (value) => {
  // 使用正则表达式限制输入
  const reg = /^\d{0,7}(\.\d{0,2})?$/
  if (!reg.test(value)) {
    // 如果不符合规则，则回退到上一次有效值
    param.unitPrice = param.unitPrice.slice(0, -1)
    total.value = param.unitPrice * param.inventory
  }else {
    total.value = param.unitPrice * param.inventory
  }
}
const handleChange = () => { 
    const unitPrice = Number(param.unitPrice) || 0
    const inventory = Number(param.inventory) || 0
    total.value = Number((unitPrice * inventory).toFixed(2))
}
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
};
const handlePeriodInput = (value) => {
  // 移除非数字字符
  let filtered = value.replace(/[^\d]/g, '');
    
    // 如果为空，设置为空字符串
    if (filtered === '') {
        param.period = '';
      return;
    }
    
    // 转换为数字
    const num = parseInt(filtered, 10);
    
    // 确保是有效的非负数
    if (!isNaN(num) && num >= 0) {
        param.period = num.toString();
    } else {
        param.period = '';
    }
}
</script>
<style lang="scss" scoped>
.city-title{
    font-weight: 500;
    font-size: 18px;
}
.city-content{
    color: #999;
}
.input-with-select{
    color: #ff0000;
}
.total{
    color: #ff0000;
    font-size: 24px;
    font-weight: 600;
}
</style>